// @flow
import React, { Component } from 'react';
import './LoadingBar.scss';

type Props = {
  start: number,
  end: number,
  timeout: number,
  interval: number,
  visible: boolean,
  done: boolean,
};
type State = {
  percent: number,
  timeout: number,
  progFunc: *,
};
class LoadingBar extends Component<Props, State> {
  constructor(props: Props, state: State) {
    super(props);
    this.state = {
      percent: this.props.start,
      timeout: this.props.timeout ? this.props.timeout : 2000,
      progFunc: window.setInterval(this.progress, this.props.interval),
    };
  }

  progress = () => {
    const { timeout, progFunc } = this.state;
    const step = ((this.props.end - this.props.start) * this.props.interval) / timeout;
    this.setState({ percent: this.state.percent + step });
    console.log(step);
    if (this.state.percent >= this.props.end) window.clearInterval(progFunc);
  };
  componentWillUnmount() {
    window.clearInterval(this.state.progFunc);
  }
  render() {
    const { done, end, visible } = this.props;
    const { percent } = this.state;
    if (!visible) return null;
    return (
      <div className="Loading-bar">
        {this.props.done === true ? (
          <div className="loadbar-progress" />
        ) : (
          <div
            className="loadbar-progress"
            style={{
              width: `${Math.max(1, Math.min(100, percent))}%`,
            }}
          />
        )}
        {percent < end && !done ? <div className="loadbar-spinner" /> : null}
      </div>
    );
  }
}

export default LoadingBar;
